package common;

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;

import com.thoughtworks.selenium.CommandProcessor;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.HttpCommandProcessor;
import com.thoughtworks.selenium.Selenium;

/**
 * Utility class for doing Selenium tests that automatigically boots the remote
 * control before the server starts and shuts down the remote control after the
 * server stops
 * 
 * @author timothystorm
 */
public class SeleniumUtil extends DefaultSelenium implements Selenium {
	private static SeleniumServer _server;

	public enum Browser {
		FIREFOX("firefox"), SAFARI("safari"), CHROME("chrome"), OPERA("opera"), IE("ieplore");

		private String _type;

		private Browser(String type) {
			_type = type;
		}

		public String getType() {
			return _type;
		}
	}

	/**
	 * Factory method for creating Selenium with defaults.
	 * 
	 * <ul>
	 * <li>host = localhost</li>
	 * <li>port = 4444</li>
	 * <li>app URL = http://localhost:8080/</li>
	 * </ul>
	 * 
	 * @param browser
	 *            target browser (firefox, ie, chrome, safari)
	 * @return
	 * @throws Exception
	 */
	public static Selenium create(Browser browser) throws Exception {
		return create(browser, "localhost", 4444, "http://localhost:8080/");
	}

	/**
	 * Factory method for creating Selenium with the provided parameters
	 * 
	 * @param host
	 *            for the app ex. "localhost"
	 * @param port
	 *            which remote control will listen on and the server will send
	 *            commands to
	 * @param browser
	 *            target browser (firefox, ie, chrome, safari)
	 * @param url
	 *            of the application ex. "http://localhost:8080/"
	 * @return
	 * @throws Exception
	 */
	public static Selenium create(Browser browser, String host, int port, String url) throws Exception {
		RemoteControlConfiguration remoteControl = new RemoteControlConfiguration();
		remoteControl.setSingleWindow(false);
		remoteControl.setPort(port);
		_server = new SeleniumServer(false, remoteControl);

		return new SeleniumUtil(new HttpCommandProcessor(host, port, browser.getType(), url));
	}

	private SeleniumUtil(CommandProcessor proc) {
		super(proc);
	}

	/**
	 * starts up the remote control before starting the server
	 */
	@Override
	public void start() {
		try {
			_server.boot();
			super.start();
		}
		catch (Exception e) {}
	}

	/**
	 * shuts down the remote control after stopping the server
	 */
	@Override
	public void stop() {
		super.stop();
		_server.stop();
	}
}
